//
//  MYCloudDiskViewController.swift
//  MYDoctor
//
//  Created by Denny on 2024/3/8.
//

import UIKit

class MYGCloudDiskCommonShareFileVC: MYGBaseController {
    var farmerModel = MYCloudDiskContentModel()
    var subFileModels = [MYCloudDiskContentModel]()
    var currentFileModel = MYCloudDiskContentModel()
    var type = 0//0全部文件夹类型 （1图片 2 视频 3文档）
    var dataSource = [MYCloudDiskContentModel]()
    lazy var headerView: MYGCloudDiskCommonShareFileHeaderView = {
        let control = MYGCloudDiskCommonShareFileHeaderView()
        control.tapDownloadCompeltion = {[weak self] in
            guard let `self` = self else {return}
            MYGCloudDiskPopManager.showDownloadUploadView(self.view)
        }
        control.tapIndexCompeltion = {[weak self] index in
            self?.type = index
            self?.configDataSource()
        }
        control.tapManagrCompeltion = {[weak self] in
            guard let `self` = self else{return}
            let vc = MYGShareManagerController()
            vc.farmerModel = self.farmerModel
            self.navigationController?.pushViewController(vc, animated: true)
        }
        return control
    }()

    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 12
        layout.minimumInteritemSpacing = 4
        var leftMargin = 12.0
        var midMargin = 8.0
        let itemWidth = (screenWidth - 2 * leftMargin - 2 * midMargin) / 3
        layout.itemSize = CGSize(width: itemWidth, height: 100)
        let control = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        control.register(UINib.init(nibName: "MYGCloudContentCell", bundle: nil), forCellWithReuseIdentifier: "MYGCloudContentCell")
        control.showsHorizontalScrollIndicator = false
        control.showsVerticalScrollIndicator = false
        control.backgroundColor = .white
        control.delegate = self
        control.dataSource = self
        control.contentInset = UIEdgeInsets(top: 0, left: leftMargin, bottom: 0, right: leftMargin)
        return control
    }()
    
    lazy var addFileBtn: UIButton = {
        let control = UIButton()
        control.setImage(UIImage.init(named: "MYG_cloudDisk_addFile"), for: .normal)
        control.addTarget(self, action: #selector(tapAddAction), for: .touchUpInside)
        return control
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "共享"
        navigationBarShow()
        setupUI()
        configDataSource()
        
        NotificationCenter.default.addObserver(self, selector: #selector(configDataSource), name: NSNotification.Name("MYCloudDiskViewController_configDataSource"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(popUpDismiss), name: NSNotification.Name("JFPopupController_dismiss"), object: nil)
    }
    
    //监听弹窗dismiss
    @objc func popUpDismiss() {
        self.dataSource = self.dataSource.map({ model in
            let obj = model
            obj.selected = false
            return obj
        })
        self.collectionView.reloadData()
    }
    
  
    func setupUI () {
        view.addSubview(headerView)
        headerView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(93)
        }
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(headerView.snp.bottom).offset(20)
            make.left.right.bottom.equalToSuperview()
        }
        view.addSubview(addFileBtn)
        addFileBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSize.init(width: 76, height: 76))
            make.bottom.equalToSuperview().offset(-bottomSafeheight - 62)
            make.right.equalToSuperview()
        }
    }
    
    override func backAction() {
        //点一次返回就减少数组中最后一个
        if self.subFileModels.count > 0 {
            //点击文件夹返回后
            if let last = self.subFileModels.last {
                self.subFileModels = self.subFileModels.filter({ model in
                    return model.id != last.id
                })
            }
            if let current = self.subFileModels.last {
                self.currentFileModel = current
            }
            headerView.tapFirstBtn()
        }else {
            super.backAction()
        }
    }
    
    @objc func configDataSource() {
        MYGLoading.show()
        var param = ["type":"\(self.type)"]
        if self.subFileModels.count > 0  && self.currentFileModel.id.count > 0 {
            //子文件夹查询
            param["pid"] = "\(self.currentFileModel.id)"
        }else {
            param["pid"] = "\(self.farmerModel.id)"
        }
        
       
        MYGNetwork<MYGMeAPI, MYCloudDiskAddFileListModel>.request(target: .netDiskFolder(param: param)) { item in
            MYGLoading.hide()
            self.dataSource = item.list
            self.collectionView.reloadData()
        } failed: { _, error in
            MYGLoading.hide()
        }
    }

    @objc func tapAddAction() {
        var pid = self.farmerModel.id
        if self.currentFileModel.id.count > 0 {
            pid = self.currentFileModel.id
        }
        MYGCloudDiskPopManager.showCommonShareAddFileAlert(self.view,fid: Int(pid) ?? 0)
    }
    
}

extension MYGCloudDiskCommonShareFileVC:UICollectionViewDataSource,UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MYGCloudContentCell", for: indexPath) as! MYGCloudContentCell
        let model = self.dataSource[indexPath.row]
        cell.bindData(model)
        cell.tapSelectedCompletion = {[weak self] data in
            guard let `self` = self else {return}
            self.dataSource = self.dataSource.map({ obj in
                let result = obj
                result.selected = (obj.id == data.id)
                return result
            })
        
            self.collectionView.reloadData()
            if data.type != 0{
                MYGCloudDiskPopManager.showEditDocmentAlert(self.view, model: data)
            }else {
                MYGCloudDiskPopManager.showEditFileAlert(self.view, model: data)
            }
            
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = self.dataSource[indexPath.row]
        if model.type == 0  {
            MYGLoading.show()
            MYGNetwork<MYGMeAPI, MYCloudDiskAddFileListModel>.request(target: .netDiskFolder(param: ["type":"\(self.type)","pid":model.id])) { item in
                MYGLoading.hide()
                self.subFileModels.append(model)
                self.currentFileModel = model
                self.dataSource = item.list
                self.collectionView.reloadData()
            } failed: { _, error in
                MYGLoading.hide()
            }
        }
    }
    
    
}
 
